package com.lagou.proxy;

import com.lagou.service.AccountService;
import com.lagou.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyFactory {

    @Autowired
    public AccountService accountService;

    @Autowired
    public TransactionManager transactionManager;

    public AccountService createAccountServiceCglibProxy(){
        AccountService service = (AccountService) Enhancer.create(accountService.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                System.out.println("先执行");
                try {
                    // 手动开启事务:调用事务管理类中的事务开启方法
                    transactionManager.beginTransaction();
                    result = method.invoke(accountService, objects);
                    // 手动提交事务
                    transactionManager.commit();
                } catch (Exception e) {
                    // 手动回滚事务
                    transactionManager.rollback();
                } finally {
                    // 手动释放资源
                    transactionManager.close();
                }
                System.out.println("后执行");
                return result;
            }
        });
        return service;
    }
}
